<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractNo">
              <a-input v-model="model.contractNo" placeholder="请输入合同编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <j-popup
                v-model="model.customerName"
                field="customerName"
                org-fields="id,cust_full_name"
                dest-fields="customerId,customerName"
                code="crm_customer_pop"
                :multi="false"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="纸质合同号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paperNo">
              <a-input v-model="model.paperNo" placeholder="请输入纸质合同号" ></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8" >
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId_dictText">
              <j-popup
                v-model="model.projectId_dictText"
                field="projectId"
                org-fields="id,project_name,customer_id,customer_name"
                dest-fields="projectId,projectId_dictText,customerId,customerName"
                code="quote_project_popup"
                :param="{customerId: model.customerId}"
                :multi="false"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractName">
              <a-input v-model="model.contractName" placeholder="请输入合同名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="销售类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="saleType">
              <j-dict-select-tag type="list" v-model="model.saleType" dictCode="crm_contract_sale_type" placeholder="请选择销售类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="销售员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <j-select-user-by-dep v-model="model.salesman" @change="salesmanChanged" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="owner">
              <j-select-user-by-dep v-model="model.owner" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractType">
              <j-dict-select-tag type="list" v-model="model.contractType" dictCode="crm_contract_type" placeholder="请选择合同类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="签约日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signDate">
              <j-date placeholder="请选择签约日期" v-model="model.signDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="截至日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expireDate">
              <j-date placeholder="请选择截至日期" v-model="model.expireDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="签署单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerSign_dictText">
              <j-popup
                v-model="model.customerSign_dictText"
                field="customerSign_dictText"
                org-fields="id,cust_full_name"
                dest-fields="customerSign,customerSign_dictText"
                code="crm_customer_pop"
                :multi="false"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="客户签约人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerMan">
              <a-input v-model="model.customerMan" placeholder="请输入客户签约人" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currencyNo">
              <j-dict-select-tag type="list" v-model="model.currencyNo" dictCode="mdm_currency,currency_name,currency_no" placeholder="请选择币种" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="1" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
<!--       子表单区域-->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="合同明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="sdContractDetailTable.loading"
          :columns="sdContractDetailTable.columns"
          :dataSource="sdContractDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added = "detailAdded"
          @valueChange = "qtyAndPriceChange">
          <div slot="buttonBefore" class="action-button">
            <a-button type="primary" icon="plus" @click="chooseQuoteProduct" :disabled="formDisabled">选单</a-button>
            <span class="gap"></span>
            <a-button type="primary" icon="plus" @click="chooseMaterial" :disabled="formDisabled">新增</a-button>
            <span class="gap"></span>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="materialPopupOnlReport" code="mdm_popup_bom_material" multi="true" @ok="addPopupCallback"/>
        <j-popup-onl-report ref="quoteProductOnlReport" code="quote_product_popup" multi="true" :param="quoteProductOnlReportParam" @ok="quoteProductPopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import {FormTypes, getRefPromise, getValuesAssign, VALIDATE_NO_PASSED} from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'SdContractForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          saleType: '01',
          contractType: '01',
          status: '01',
          currencyNo: 'RMB',
        },
        quoteProductOnlReportParam:{},
        qtyAndPriceModifyFlag: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           contractNo: [
              { required: true, message: '请输入合同编号!'},
           ],
          customerName: [
              { required: true, message: '请输入客户!'},
           ],
        },
        refKeys: ['sdContractDetail', ],
        tableKeys:['sdContractDetail', ],
        activeKey: 'sdContractDetail',
        // 销售合同明细
        sdContractDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode: 'mdm_popup_bom_material',
              orgFields: 'material_id,material_code,material_desc,material_unit_code',
              destFields: 'materialId,materialNo,materialDesc,unit',
              width:"260px",
              placeholder: '请选择${title}',
              defaultValue:'',
              jEditableParam: { jEditableInstance: null, jEditableColName: 'materialId', paramColName: 'materialIdList'},
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '数量',
              key: 'qty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              validateRules: [
                { required: true, message: '${title}不能为空' },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数' },
              ],
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '金额',
              key: 'sumPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              scale: 2,
              statistics: true,
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"260px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '不含税单价',
              key: 'unitPriceNotax',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '不含税金额',
              key: 'sumPriceNotax',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              scale: 2,
              statistics: true,
            },
            {
              title: '税率',
              key: 'taxRate',
              type: FormTypes.select,
              dictCode: "mdm_tax_rate,value,value",
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0.13',
            },
            {
              title: '税额',
              key: 'taxMoney',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              scale: 2,
              statistics: true,
              disabled: true
            },
            {
              title: '销单数量',
              key: 'salesQty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              disabled: true,
            },
            {
              title: '交货数量',
              key: 'deliveryQty',
              type: FormTypes.inputNumber,
              width:"140px",
              defaultValue:'0',
              disabled: true,
            },
            {
              title: '行号',
              key: 'lineNo',
              type: FormTypes.inputNumber,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: 'materialId',
              key: 'materialId',
              type:"hidden"
            },
            {
              title: 'materialNo',
              key: 'materialNo',
              type:"hidden"
            },
            {
              title: 'materialSpec',
              key: 'materialSpec',
              type:"hidden"
            },
            {
              title: 'materialGraphNo',
              key: 'materialGraphNo',
              type:"hidden"
            },
            {
              title: 'materialMaterial',
              key: 'materialMaterial',
              type:"hidden"
            },
            {
              title: 'materialName',
              key: 'materialName',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/sd/contract/add",
          edit: "/sd/contract/edit",
          queryById: "/sd/contract/queryById",
          genCode: "/mdm/codeRule/genCode",
          sysUserDepInfo: "/sys/user/queryDepInfoByUsername",
          sdContractDetail: {
            list: '/sd/contract/querySdContractDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.genBillNo();
        this.sdContractDetailTable.dataSource=[]
      },
      genBillNo(){
        this.confirmLoading = true;
        getAction(this.url.genCode, {codeType: '03'}).then(res => {
          if (res.success) {
            this.model.contractNo = res.result;
          }
        }).finally(() => {
          this.confirmLoading = false;
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.sdContractDetail.list, params, this.sdContractDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          sdContractDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(value,row){
       this.model = Object.assign(this.model, row);
     },
      detailAdded: function (obj) {
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if(rows.length > 1){
          let lastId = editTable.getCleanId(rows[rows.length-2].id)
          let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
          num = parseInt(values[0].lineNo) + 10
        }
        editTable.setValues([{rowKey: obj.row.id, values:{lineNo: num}}])
      },
      qtyAndPriceChange(parm){
        if(parm && parm['column'] && parm['row'] && parm['target']){
          let cols = ['qty','unitPrice','sumPrice','unitPriceNotax','sumPriceNotax','taxRate','taxMoney'];
          let key = parm.column.key;
          if(cols.includes(key) && !this.qtyAndPriceModifyFlag){
            let valueObj = {}
            let editableTable = parm['target'];
            let qty = parm.row[cols[0]] || 0;
            let taxRate = Number(parm.row[cols[5]] || 0);
            //修改数量
            if(key === cols[0]){
              //计算金额
              let unitPrice = parm.row[cols[1]] || 0;
              let sumPrice = Math.round(unitPrice * qty * 100)/100;
              //计算税额
              let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
              //计算不含税金额
              let sumPriceNotax = Math.round((sumPrice - taxMoney) *100)/100;
              let unitPriceNotax = qty == 0 ? 0 : Math.round(sumPriceNotax * 100 / qty )/100;
              //
              valueObj = {[cols[2]]: sumPrice, [cols[4]]: sumPriceNotax, [cols[3]]: unitPriceNotax, [cols[6]]: taxMoney}
            }
            // 修改单价、金额
            if(key === cols[1] || key === cols[2]){
              let unitPrice, sumPrice
              if(key === cols[1]){
                //计算金额
                unitPrice = parm.row[cols[1]] || 0;
                sumPrice = Math.round(unitPrice * qty * 100)/100;
              }
              if(key === cols[2]){
                //计算单价
                sumPrice = parm.row[cols[2]] || 0;
                unitPrice = qty == 0 ? 0 : Math.round(sumPrice / qty * 100)/100;
              }
              //计算税额
              let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
              //计算不含税金额、不含税单价
              let sumPriceNotax = Math.round((sumPrice - taxMoney)*100)/100;
              let unitPriceNotax = qty == 0 ? 0 : Math.round(sumPriceNotax * 100 / qty )/100;
              //
              valueObj = {[cols[1]]: unitPrice,[cols[2]]: sumPrice, [cols[3]]: unitPriceNotax, [cols[4]]: sumPriceNotax, [cols[6]]: taxMoney}
            }
            // 修改不含税单价、不含税金额
            if(key === cols[3] || key === cols[4]){
              let unitPriceNotax, sumPriceNotax
              if(key === cols[3]){
                //计算不含税金额
                unitPriceNotax = parm.row[cols[3]] || 0;
                sumPriceNotax = Math.round(unitPriceNotax * qty * 100)/100;
              }
              if(key === cols[4]){
                //计算不含税单价
                sumPriceNotax = parm.row[cols[4]] || 0;
                unitPriceNotax = qty == 0 ? 0 : Math.round(sumPriceNotax / qty * 100)/100;
              }
              //计算税额
              let taxMoney = Math.round(sumPriceNotax * taxRate * 100)/100
              //计算金额、单价
              let sumPrice = Math.round((sumPriceNotax + taxMoney)*100)/100
              let unitPrice = qty == 0 ? 0 : Math.round(sumPrice / qty * 100) /100;
              //
              valueObj = {[cols[1]]: unitPrice,[cols[2]]: sumPrice, [cols[3]]: unitPriceNotax, [cols[4]]: sumPriceNotax, [cols[6]]: taxMoney}
            }
            // 修改税率
            if(key === cols[5]){
              let sumPrice = parm.row[cols[2]] || 0;
              //计算税额
              let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
              //计算不含税金额、不含税单价
              let sumPriceNotax = Math.round((sumPrice - taxMoney)*100)/100;
              let unitPriceNotax = qty == 0 ? 0 : Math.round(sumPriceNotax / qty * 100) /100;
              //
              valueObj = {[cols[3]]: unitPriceNotax, [cols[4]]: sumPriceNotax, [cols[6]]: taxMoney}
            }
            //更新
            this.qtyAndPriceModifyFlag = true
            editableTable.setValues([{rowKey: parm.row.id, values: valueObj}]);
            this.qtyAndPriceModifyFlag = false
            // 重新计算统计列
            editableTable.recalcOneStatisticsColumn(cols[2]);
            editableTable.recalcOneStatisticsColumn(cols[4]);
            editableTable.recalcOneStatisticsColumn(cols[6]);
          }
        }
      },
      chooseMaterial(){
        this.$refs.materialPopupOnlReport.show();
      },
      chooseQuoteProduct(){
        if(!this.model.projectId){
          this.$message.error("请先选择项目！")
          return
        }
        this.quoteProductOnlReportParam.projectId = this.model.projectId;
        let contractDetailEditTable = this.$refs[this.refKeys[0]];
        let choosedMaterialIdArr = getValuesAssign(contractDetailEditTable,"materialId");
        if(choosedMaterialIdArr.length > 0){
          this.quoteProductOnlReportParam.materialIds = choosedMaterialIdArr.join(',');
        }else{
          this.quoteProductOnlReportParam.materialIds = '';
        }
        this.$refs.quoteProductOnlReport.show();
      },
      addPopupCallback(rows){
        if(rows && rows.length > 0){
          let contractDetailEditTable = this.$refs[this.refKeys[0]];
          let oldData = contractDetailEditTable.getValuesSync();
          let column = this.sdContractDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = column.orgFields.split(',');
          let destFieldsArr = column.destFields.split(',');
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              contractDetailEditTable.add();
            }
            addRow = contractDetailEditTable.rows[contractDetailEditTable.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            contractDetailEditTable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },

      quoteProductPopupCallback(rows){
        if(!rows || rows.length == 0){
          return;
        }
        let contractDetailEditTable = this.$refs[this.refKeys[0]];
        let oldData = contractDetailEditTable.getValuesSync();
        let column = this.sdContractDetailTable.columns.find(col=>col.key === 'materialDesc')
        let orgFieldsArr = ['material_id','material_no','material_desc','unit','qty','unit_price','sum_price'];
        let destFieldsArr = ['materialId','materialNo','materialDesc','unit','qty','unitPrice','sumPrice'];
        let addRow, addData
        for(let i =0; i< rows.length; i++){
          if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
            contractDetailEditTable.add();
          }
          addRow = contractDetailEditTable.rows[contractDetailEditTable.rows.length - 1];
          // key转换
          for(let j=0; j<orgFieldsArr.length; j++){
            rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
            if(destFieldsArr[j] !== orgFieldsArr[j]){
              delete rows[i][orgFieldsArr[j]]
            }
          }
          addData = Object.assign({},rows[i])
          contractDetailEditTable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          // 计算税额、不含税金额、不含税单价
          let taxRate = 0.13;
          let sumPrice = addData.sumPrice || 0;
          let qty = addData.qty || 0;
          let taxMoney = this.$math.round(this.$math.multiply(this.$math.divide(sumPrice, this.$math.add(1, taxRate)), taxRate));
          let sumPriceNotax = this.$math.round(this.$math.subtract(sumPrice, taxMoney));
          let unitPriceNotax = qty == 0 ? 0 : this.$math.round(this.$math.divide(sumPriceNotax, qty));
          contractDetailEditTable.setValues([{rowKey: addRow.id, values: {taxMoney: taxMoney, sumPriceNotax: sumPriceNotax, unitPriceNotax:unitPriceNotax}}]);
        }

      },
      salesmanChanged(storeValues){
        let that = this;
        if(storeValues){
          let params = {username: storeValues};
          getAction(this.url.sysUserDepInfo, params).then((res) => {
            if (res.success) {
              if(res.result){
                that.model['salesDept'] = res.result.orgCodes.split(',',1)[0];
              }
            }
          })
        }else{
          that.model['salesDept'] = '';
        }
      }
    }
  }
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}
.gap {
  padding-left: 8px;
}
</style>